package com.myeclipse.search;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.eclipse.jface.viewers.*;
import org.eclipse.search.ui.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.IPageSite;


public class SearchResultPage implements ISearchResultPage {

	private TableViewer tableViewer;
	protected SearchResult searchResult;
	protected ISearchResultViewPart viewPart;
	protected ISearchResultListener listener;
	protected String id;
	private IPageSite pageSite;
	private Composite control;
	
	public SearchResultPage(){
		this.listener=new ISearchResultListener(){
			public void searchResultChanged(SearchResultEvent e){
				//SearchResultPage.this.handleSearchResultChanged(e);
			}
		};
	}
	
	protected void handleSearchResultChanged(SearchResultEvent e) {
		// TODO Auto-generated method stub
		//System.out.println("test");
//		if (e instanceof MatchEvent){ 
//            MatchEvent event = (MatchEvent) e; 
//            if(event.getKind() == MatchEvent.REMOVED_ALL){ 
//                postClear();                
//            } 
//            else{ 
//                postUpdate(((MatchEvent) e).getMatches()); 
//            } 
//        }        

	}

	@Override
	public IPageSite getSite() {
		// TODO Auto-generated method stub
		return pageSite;
	}

	@Override
	public void init(IPageSite site) throws PartInitException {
		// TODO Auto-generated method stub

		this.pageSite=site;
	}

	/* Set the SearchResultPage Layout and Content in this function. Use TableViewer to show the results */
	@Override
	public void createControl(Composite parent) {
		// TODO Auto-generated method stub
		control = new Composite(parent, SWT.NONE);
		control.setLayout(new FillLayout());
		tableViewer = new TableViewer(control, SWT.SINGLE|SWT.FULL_SELECTION);
		Table table=tableViewer.getTable();
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		//-------------------------------------Set TableView Header-------------------------------------
		String[] columnNames=new String[]{"Name","Type","LineCount","MatchCount","Source"};
		int[] columnWidths=new int[]{500,70,80,80,100};
		int[] columnAlignments=new int[]{SWT.LEFT,SWT.LEFT,SWT.CENTER,SWT.CENTER,SWT.CENTER};
		for(int i=0;i<columnNames.length;i++){
			TableColumn tableColumn=new TableColumn(table,columnAlignments[i]);
			tableColumn.setText(columnNames[i]);
			tableColumn.setWidth(columnWidths[i]);
		}
		
		//------------------------------------Set Label provider------------------------------------------
		tableViewer.setLabelProvider(new ITableLabelProvider(){
			@Override
			public void addListener(ILabelProviderListener listener) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void dispose() {
				// TODO Auto-generated method stub
				
			}

			@Override
			public boolean isLabelProperty(Object element, String property) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void removeListener(ILabelProviderListener listener) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public Image getColumnImage(Object element, int columnIndex) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public String getColumnText(Object element, int columnIndex) {
				// TODO Auto-generated method stub
				Code code=(Code)element;
				switch (columnIndex) {
				case 0:
					return code.getName();
					//return "First Name";
				case 1:
					return code.getTpye();
					//return "Last Name";

				case 2:
					return code.getLinecount();
				case 3:
					return code.getMatchcount();
				case 4:
					return code.getSource();
				default:
					break;
				}
				return null;
			}
			});
		
		//------------------------------------Set Content provider------------------------------------------
		tableViewer.setContentProvider(new IStructuredContentProvider(){
			SearchResult result;
			@Override
			public void dispose() {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void inputChanged(Viewer viewer, Object oldInput,
					Object newInput) {
				// TODO Auto-generated method stub
				//System.out.println("Input changed: old="+oldInput + ", new="+ newInput);
				if (newInput != oldInput) {
//					if (oldInput != null) {
//						((SearchResult) oldInput).removeAllListeners();
//					}
					result = (SearchResult) newInput;
					if (result != null)
						result.addListener(new ISearchResultListener() {
							public void searchResultChanged(SearchResultEvent e) {
								Display.getDefault().asyncExec(new Runnable() {
									public void run() {
										tableViewer.refresh();
									}
								});
							}
						});
				}
				viewer.refresh();
			}

			/*Get search result from the parameter:inputElement*/
			@Override
			public Object[] getElements(Object inputElement) {
				// TODO Auto-generated method stub
				ArrayList<Code> list=((SearchResult)inputElement).getResult();
				return list.toArray();
			}});
		
		//------------------------------------Processing User's Double click--------------------------------
		tableViewer.addDoubleClickListener(new IDoubleClickListener(){

			@Override
			public void doubleClick(DoubleClickEvent event) {
				// TODO Auto-generated method stub
				IStructuredSelection selection =(IStructuredSelection)event.getSelection();
				Code code=(Code)selection.getFirstElement();
				
				//-----------------------------manipulate code here---------------------------------
				//present the source code
				//System.out.println(code.firstName+code.lastName);
				String codeURL="http://searchco.de/codesearch/raw/"+code.getId();
				URL url;
				try {
					//Show the source code in the web browser.
					url = new URL(codeURL);
					try {
						PlatformUI.getWorkbench(). getBrowserSupport().createBrowser("CodeSearchBrowser").openURL(url);
					} catch (PartInitException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (MalformedURLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}});
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public Control getControl() {
		// TODO Auto-generated method stub
		return control;
	}

	@Override
	public void setActionBars(IActionBars actionBars) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub
		tableViewer.getControl().setFocus();
	}

	@Override
	public Object getUIState() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setInput(ISearchResult search, Object uiState) {
		// TODO Auto-generated method stub

		ISearchResult oldSearch=(ISearchResult)this.tableViewer.getInput();
		this.tableViewer.setInput(null);
		if(oldSearch!=null){
			oldSearch.removeListener(this.listener);
		}
		this.searchResult=(SearchResult)search;
		if(searchResult!=null /*&& searchResult.getElements().size()>0*/)
		{
			search.addListener(this.listener);
			this.tableViewer.setInput(search);
			if(uiState instanceof ISelection)
				this.tableViewer.setSelection((ISelection)uiState,true);
		}
		
		//tableViewer.setInput(search);
	}

	@Override
	public void setViewPart(ISearchResultViewPart part) {
		// TODO Auto-generated method stub
		viewPart=part;
	}

	@Override
	public void restoreState(IMemento memento) {
		// TODO Auto-generated method stub

	}

	@Override
	public void saveState(IMemento memento) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setID(String id) {
		// TODO Auto-generated method stub

		this.id=id;
	}

	@Override
	public String getID() {
		// TODO Auto-generated method stub
		return id;
	}

	@Override
	public String getLabel() {
		// TODO Auto-generated method stub
		String label="Results found via the query: "+searchResult.getQuery().getLabel();
		return label;
	}


}
